import { Ware } from '../core'
import { Options, Context, Template } from './types'

import confirm from './confirm'
import resolve from './resolve'
import load from './load'
import inquire from './inquire'
import setup from './setup'
import prepare from './prepare'
import rename from './rename'
import render from './render'
import emit from './emit'
import install from './install'
import init from './init'
import complete from './complete'

// TODO: require lazy ??

// 中间件机制
const creator = new Ware<Context>()

// 使用的环节工作流
creator.use(confirm)
creator.use(resolve)
creator.use(load)
creator.use(inquire)
creator.use(setup)
creator.use(prepare)
creator.use(rename)
creator.use(render)
creator.use(emit)
creator.use(install)
creator.use(init)
creator.use(complete)

// 导出异步函数
export default async (template: string, project: string = '.', options: Options = {}): Promise<void> => {
  // required arguments
  // 传入必要参数  lint不让写 !template  可能性过多不确定性
  if (template == null || template === '') {
    throw new Error('Missing required argument: `template`.')
  }

  // create context  创建上下文
  const context = {
    // 模板目录
    template,
    // 项目名称
    project,
    // 参数选项
    options,
    src: '',
    dest: '',
    // 不会有原型 创建一个无原型的对象
    config: Object.create(null),
    answers: Object.create(null),
    files: []
  }

  // running creator
  // 将context放入中间件并执行工作流
  await creator.run(context)
}

export { Options, Context, Template }
